#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>

typedef int(*func)(int,int);

int add(int a,int b)
{
	return a+b;
}
int sub(int a,int b)
{
	return a-b;
}
int mul(int a,int b)
{
	return a*b;
}
int division(int a,int b)
{
	return a/b;
}
int main()
{

	func fun[4]={add,sub,mul,division};

	pid_t childId = fork(); 
	if(childId<0)
	{
		//申请失败
		printf("fork::%s",strerror(errno));
		exit(1);
	}
	else if(childId>0)
	{
		//父进程
		int cur=5;
		while(cur--)
		{
			printf("parent: pid=%d : ppid=%d \n",getpid(),getppid());
			sleep(1);
		}
		int status=0;
		int flag=10;
		pid_t rid=0;
		do
		{
			if (rid!=childId)
			{
				rid = waitpid(childId, &status, WNOHANG);
				if (rid>0)
				{
					if(WIFEXITED(status))
					{
						printf("wait success rid: %d| exit code: %d| exit signal: %d\n", rid, WEXITSTATUS(status), status&0x7F);
					}
					else
					{
						printf("exit error\n");
					}
					//printf("wait success rid: %d| exit code: %d| exit signal: %d\n", rid, (status>>8)&0xFF, status&0x7F);
				}
				else if(rid<0)
				{
					printf("wait failed rid: %d: %s\n",rid,strerror(errno));
				}
				printf("rid-> %d\n",rid);
			}
			//其他工作
			if (flag!=0)
			{
				int p =fun[flag%4](16,4);
				printf("其他工作fun-> %d\n",p);
				flag--;
			}

			sleep(1);
		}while((flag!=0)||(rid==childId));
	}
	else
	{
		//子进程
		int cur=20;
		while(cur--)
		{
			printf("child : pid=%d : ppid=%d \n",getpid(),getppid());
			sleep(1);
		}
	}	
	return 0;
}
